package com.hq.fxh.No0_ChengQu.Login;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hq.fxh.CustomerView.TimeCount;
import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Intefers.NetworkSubscriber;
import com.hq.fxh.Modle.CreateMemberRes;
import com.hq.fxh.Modle.SelectByMobileRes;
import com.hq.fxh.No0_ChengQu.Activity.BaseActivity;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Activity.item.ToastUtils;
import com.hq.fxh.No3_TuiGuang.MyMoBan.ClearableEidtText;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Config;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Model.CommonRes;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Model.GetWebUrlRes;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Model.WebBean;
import com.hq.fxh.R;
import com.hq.fxh.Utils.CheckUtils;
import com.hq.fxh.Utils.IntentUtils;
import com.hq.fxh.Utils.Tool;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;

/**
 * @author 大圣
 * @ClassName RegisterActivity
 * @Description :
 * @Created 16/5/20
 * @Email qwqe601660957@163.com
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    protected ImageView toolbarImageBack;
    protected LinearLayout toolbarLayoutBack;
    protected TextView toolBarTvTitle;
    protected LinearLayout toolbarContent;
    protected LinearLayout layoutContent;
    protected LinearLayout registerLayoutContent;
    protected TextView tvRegisterToLogin;
    protected ImageView imageRegisterPhone;
    protected ImageView imageRegisterCode;
    protected ImageView imageRegisterPassword;
    /**
     * 手机号输入框
     */
    private ClearableEidtText etPhoneNumber;
    /**
     * 获取短信验证码按钮
     */
    private TextView tvGetCheckCode;
    /**
     * 验证码输入框
     */
    private ClearableEidtText etCheckCode;
    /**
     * 密码输入框
     */
    private ClearableEidtText etPassword;
    /**
     * 密码确认输入框
     */
    /**
     * 注册按钮
     */
    private Button btnRegister;
    private TextView tvRegisterAgreement;
    /**
     * 获取验证码后倒计时
     */
    private TimeCount timeCount;
    /**
     * 是否接受协议
     */
    private List<WebBean> webBean;
    private String weburl;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        setSysColor(R.color.red, true);
        etPhoneNumber = (ClearableEidtText) findViewById(R.id.etPhoneNumber);
        tvGetCheckCode = (TextView) findViewById(R.id.tvGetCheckCode);
        etCheckCode = (ClearableEidtText) findViewById(R.id.etCheckCode);
        etPassword = (ClearableEidtText) findViewById(R.id.etPassword);
        btnRegister = (Button) findViewById(R.id.btnRegister);
        tvRegisterAgreement = (TextView) findViewById(R.id.tvRegisterAgreement);
        toolbarImageBack = (ImageView) findViewById(R.id.toolbar_image_back);
        toolbarLayoutBack = (LinearLayout) findViewById(R.id.toolbar_Layout_back);
        toolbarLayoutBack.setOnClickListener(RegisterActivity.this);
        toolBarTvTitle = (TextView) findViewById(R.id.toolBar_tv_Title);
        toolbarContent = (LinearLayout) findViewById(R.id.toolbar_Content);
        layoutContent = (LinearLayout) findViewById(R.id.layout_Content);
        registerLayoutContent = (LinearLayout) findViewById(R.id.register_layout_Content);
        tvRegisterToLogin = (TextView) findViewById(R.id.tv_register_toLogin);
        tvRegisterToLogin.setOnClickListener(RegisterActivity.this);
        imageRegisterPhone = (ImageView) findViewById(R.id.image_register_phone);
        imageRegisterCode = (ImageView) findViewById(R.id.image_register_Code);
        imageRegisterPassword = (ImageView) findViewById(R.id.image_register_Password);
    }

    @Override
    protected void initData() {
        toolBarTvTitle.setText("用户注册");
        registerListener();
        timeCount = new TimeCount(60 * 1000, 1000, tvGetCheckCode);
        etPassword.setFilters(new InputFilter[]{
                new InputFilter.LengthFilter(20),
                new InputFilter() {

                    @Override
                    public CharSequence filter(CharSequence source, int start,
                                               int end, Spanned dest, int dstart, int dend) {

                        if (isCN(source.toString())) {
                            if (dstart >= 0) {
                                etPassword.setSelection(dstart);
                                return "";
                            } else {
                                if (source.length() + dest.length() > 0) {
                                    return source.subSequence(start, start + 0 - dest.length());
                                } else {
                                    return source;
                                }
                            }
                        } else {
                            return source;
                        }
                    }
                }
        });
        Tool.setEditorChange(etCheckCode, imageRegisterCode, R.mipmap.dl_yanzheng, R.mipmap.dl_yanzheng_to);
        Tool.setEditorChange(etPassword, imageRegisterPassword, R.mipmap.dl_mima, R.mipmap.dl_mima_to);
        Tool.setEditorChange(etPhoneNumber, imageRegisterPhone, R.mipmap.dl_shouji, R.mipmap.dl_shouji_to);

    }


    @Override
    protected void onResume() {
        super.onResume();
        JAnalyticsInterface.onPageStart(this, "注册");
    }

    @Override
    protected void onPause() {
        super.onPause();
        JAnalyticsInterface.onPageEnd(this, "注册");
    }

    public boolean isCN(String str) {
        try {
            byte[] bytes = str.getBytes("UTF-8");
            if (bytes.length == str.length()) {
                return false;
            } else {
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void registerListener() {
        tvGetCheckCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCheckCode();
            }
        });
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //isRegister();
                register();
            }
        });
        tvRegisterAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webBean = new ArrayList<>();
                UserServiceImpl.getWebUrl(0 + "", new NetworkSubscriber<GetWebUrlRes>() {
                    @Override
                    public int onSuccess(GetWebUrlRes data) {
                        super.onSuccess(data);
                        if (data != null && data.getCode() == 0) {
                            webBean.addAll(data.getData());
                            for (int i = 0; i < webBean.size(); i++) {
                                if (webBean.get(i).getCode().equals("regagreement")) {
                                    weburl = webBean.get(i).getUrl();
                                }
                            }
                        } else {
                            ToastUtils.show(RegisterActivity.this, data.getMsg());
                        }
                        return 0;
                    }
                });

                Bundle pBundle = new Bundle();
                pBundle.putString("title", "注册协议");
                pBundle.putString(Config.URL, weburl);
                IntentUtils.openActivity(RegisterActivity.this, WebActivity.class, pBundle);
            }
        });
    }

    /**
     * 获取验证码
     */
    private void getCheckCode() {
        String phoneNum = checkPhone();
        if (TextUtils.isEmpty(phoneNum)) {
            return;
        }
        UserServiceImpl.sendMsg(phoneNum, 1, new NetworkSubscriber<CommonRes>() {
            @Override
            public int onSuccess(CommonRes data) {
                super.onSuccess(data);
                if (data != null && data.getCode() == 0) {
//                    timeCount.onFinish();
                } else {
                    ToastUtils.show(RegisterActivity.this, data.getMsg());
                }
                return 0;
            }
        });

        timeCount.start();
    }

    /**
     * 根据手机号码查询会员（会员是否已注册）
     */
    private void isRegister() {
        String phoneNum = checkPhone();
        if (TextUtils.isEmpty(phoneNum)) {
        }
        UserServiceImpl.selectByMobile(phoneNum, new NetworkSubscriber<SelectByMobileRes>() {
            @Override
            public int onSuccess(SelectByMobileRes data) {
                super.onSuccess(data);
                int total = data.getTotal();
                if (total == 0) {
                    register();
                } else if (total > 0) {
                    ToastUtils.show(RegisterActivity.this, "该号码已注册");
                    IntentUtils.openActivity(RegisterActivity.this, LoginActivity.class);
                    finish();
                }
                return total;
            }
        });
    }

    /**
     * 创建会员信息(注册)
     *
     * @return
     */
    private void register() {
        String phoneNum = checkPhone();
        if (TextUtils.isEmpty(phoneNum)) {
        }
        String checkCode = CheckUtils.checkEditText(etCheckCode);
        if (TextUtils.isEmpty(checkCode)) {
            ToastUtils.show(this, "验证码不能为空");
        }
        String password = CheckUtils.checkEditText(etPassword);
        if (TextUtils.isEmpty(password)) {
            ToastUtils.show(this, "密码不能为空");
        } else if (password.length() < 6) {
            ToastUtils.show(this, "密码不能小于6位");
            return;
        }

        UserServiceImpl.createMember(phoneNum, password, checkCode, new NetworkSubscriber<CreateMemberRes>() {
            @Override
            public int onSuccess(CreateMemberRes data) {
                super.onSuccess(data);
                if (data != null && data.getCode() == 0) {
                    ToastUtils.show(RegisterActivity.this, "注册成功");
                    IntentUtils.openActivity(RegisterActivity.this, LoginActivity.class);
                    finish();
                } else {
                    ToastUtils.show(RegisterActivity.this, data.getMsg());
                }
                return 0;
            }
        });
    }

    public String checkPhone() {
        String phoneNum = CheckUtils.checkEditText(etPhoneNumber);
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtils.show(this, "手机号不能为空");
            return "";
        }
        if (!CheckUtils.isMobileNumber(phoneNum)) {
            ToastUtils.show(this, "手机号输入有误");
            return "";
        }
        return phoneNum;
    }


    public static String Md5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.toolbar_Layout_back) {
            finish();
        } else if (view.getId() == R.id.tv_register_toLogin) {

            startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
            finish();

        }
    }
}
